<template>
  <div class="creator-upload-container">
    <n-card class="upload-card">
      <template #header>
        <div class="card-header">
          <h1>上传素材</h1>
          <n-button @click="goBack">
            <template #icon><n-icon><ArrowBackOutline /></n-icon></template>
            返回市场
          </n-button>
        </div>
      </template>
      
      <n-tabs v-model:value="activeTab" type="line" animated>
        <n-tab-pane name="basic" tab="基本信息">
          <n-form
            ref="formRef"
            :model="uploadForm"
            :rules="rules"
            label-placement="left"
            label-width="120"
            require-mark-placement="right-hanging"
          >
            <n-form-item label="素材名称" path="name">
              <n-input v-model:value="uploadForm.name" placeholder="输入素材名称" />
            </n-form-item>
            
            <n-form-item label="素材类型" path="type">
              <n-select
                v-model:value="uploadForm.type"
                :options="typeOptions"
                placeholder="选择素材类型"
              />
            </n-form-item>
            
            <n-form-item label="素材分类" path="category">
              <n-cascader
                v-model:value="uploadForm.category"
                :options="categoryOptions"
                placeholder="选择素材分类"
                check-strategy="child"
              />
            </n-form-item>
            
            <n-form-item label="素材标签" path="tags">
              <n-dynamic-tags v-model:value="uploadForm.tags" />
              <n-text depth="3">添加标签可以让用户更容易找到您的素材</n-text>
            </n-form-item>
            
            <n-form-item label="素材描述" path="description">
              <n-input
                v-model:value="uploadForm.description"
                type="textarea"
                placeholder="描述您的素材..."
                :autosize="{ minRows: 4, maxRows: 8 }"
              />
            </n-form-item>
            
            <n-form-item label="价格设置" path="price">
              <n-radio-group v-model:value="uploadForm.isPaid" name="price">
                <n-space>
                  <n-radio :value="false">免费</n-radio>
                  <n-radio :value="true">付费</n-radio>
                </n-space>
              </n-radio-group>
              
              <div v-if="uploadForm.isPaid" class="price-input">
                <n-input-number
                  v-model:value="uploadForm.price"
                  :min="1"
                  :precision="2"
                  :step="5"
                >
                  <template #prefix>￥</template>
                </n-input-number>
              </div>
            </n-form-item>
            
            <n-form-item label="许可证选择" path="license">
              <n-select
                v-model:value="uploadForm.license"
                :options="licenseOptions"
                placeholder="选择许可证类型"
              />
            </n-form-item>
          </n-form>
          
          <div class="form-actions">
            <n-space justify="end">
              <n-button @click="resetForm">重置</n-button>
              <n-button type="primary" @click="nextStep">下一步</n-button>
            </n-space>
          </div>
        </n-tab-pane>
        
        <n-tab-pane name="files" tab="文件上传">
          <div class="upload-section">
            <n-upload
              v-model:file-list="uploadFiles"
              directory-dnd
              multiple
              :max="10"
              :default-upload="false"
            >
              <n-upload-dragger>
                <div class="upload-trigger">
                  <n-icon size="48" :depth="3">
                    <CloudUploadOutline />
                  </n-icon>
                  <n-text style="margin-top: 12px">
                    点击或拖动文件到此区域上传
                  </n-text>
                  <n-p depth="3" style="margin: 8px 0 0 0">
                    支持单个或批量上传，最多可上传10个文件
                  </n-p>
                </div>
              </n-upload-dragger>
            </n-upload>
            
            <div class="upload-tips">
              <n-alert title="上传提示" type="info">
                <template #icon>
                  <n-icon>
                    <InformationCircleOutline />
                  </n-icon>
                </template>
                <ol>
                  <li>角色素材请上传PNG图片，建议分辨率不低于1024x1024</li>
                  <li>场景素材建议上传PNG或JPG格式，分辨率不低于1920x1080</li>
                  <li>音效素材支持WAV、MP3格式，不超过10MB</li>
                  <li>请确保您拥有所上传素材的版权或使用权</li>
                </ol>
              </n-alert>
            </div>
          </div>
          
          <div class="thumbnail-section">
            <n-divider>素材缩略图</n-divider>
            
            <div class="thumbnail-upload">
              <n-upload
                v-model:file-list="thumbnailFile"
                :max="1"
                :default-upload="false"
                accept="image/*"
                list-type="image-card"
              >
                上传缩略图
              </n-upload>
              
              <n-text depth="3">
                缩略图将显示在素材市场中，建议尺寸为300x200像素
              </n-text>
            </div>
          </div>
          
          <div class="preview-section" v-if="uploadForm.type === 'character' || uploadForm.type === 'scene'">
            <n-divider>预览图</n-divider>
            
            <div class="preview-upload">
              <n-upload
                v-model:file-list="previewFiles"
                multiple
                :max="5"
                :default-upload="false"
                accept="image/*"
                list-type="image-card"
              >
                上传预览图
              </n-upload>
              
              <n-text depth="3">
                最多可上传5张预览图，用户可在素材详情页浏览
              </n-text>
            </div>
          </div>
          
          <div class="form-actions">
            <n-space justify="end">
              <n-button @click="prevStep">上一步</n-button>
              <n-button type="primary" @click="nextStep">下一步</n-button>
            </n-space>
          </div>
        </n-tab-pane>
        
        <n-tab-pane name="preview" tab="预览确认">
          <div class="preview-container">
            <div class="preview-item">
              <div class="preview-label">素材名称</div>
              <div class="preview-value">{{ uploadForm.name }}</div>
            </div>
            
            <div class="preview-item">
              <div class="preview-label">素材类型</div>
              <div class="preview-value">{{ getTypeLabel(uploadForm.type) }}</div>
            </div>
            
            <div class="preview-item">
              <div class="preview-label">素材分类</div>
              <div class="preview-value">{{ getCategoryLabel(uploadForm.category) }}</div>
            </div>
            
            <div class="preview-item">
              <div class="preview-label">素材标签</div>
              <div class="preview-value">
                <n-space>
                  <n-tag v-for="tag in uploadForm.tags" :key="tag" size="small">{{ tag }}</n-tag>
                </n-space>
              </div>
            </div>
            
            <div class="preview-item">
              <div class="preview-label">素材描述</div>
              <div class="preview-value description">{{ uploadForm.description }}</div>
            </div>
            
            <div class="preview-item">
              <div class="preview-label">价格设置</div>
              <div class="preview-value">{{ uploadForm.isPaid ? `￥${uploadForm.price}` : '免费' }}</div>
            </div>
            
            <div class="preview-item">
              <div class="preview-label">许可证类型</div>
              <div class="preview-value">{{ getLicenseLabel(uploadForm.license) }}</div>
            </div>
            
            <div class="preview-item">
              <div class="preview-label">待上传文件</div>
              <div class="preview-value">
                <n-list bordered>
                  <n-list-item v-for="file in uploadFiles" :key="file.id">
                    <n-thing :title="file.name">
                      <template #description>
                        <span>{{ formatFileSize(file.file?.size) }}</span>
                      </template>
                    </n-thing>
                  </n-list-item>
                </n-list>
              </div>
            </div>
            
            <div class="preview-item" v-if="thumbnailFile.length > 0">
              <div class="preview-label">缩略图预览</div>
              <div class="preview-value">
                <div class="thumbnail-preview">
                  <img :src="getThumbnailUrl(thumbnailFile[0])" alt="缩略图预览">
                </div>
              </div>
            </div>
          </div>
          
          <div class="submit-section">
            <n-alert title="上传须知" type="warning">
              <template #icon>
                <n-icon>
                  <AlertCircleOutline />
                </n-icon>
              </template>
              <p>提交后，您的素材将进入审核流程，审核通过后才会在市场中显示。</p>
              <p>您确认所上传的素材不侵犯任何第三方的知识产权或其他权利。</p>
            </n-alert>
            
            <n-checkbox v-model:checked="termsAccepted" class="terms-checkbox">
              我已阅读并同意《素材上传协议》和《社区规范》
            </n-checkbox>
          </div>
          
          <div class="form-actions">
            <n-space justify="end">
              <n-button @click="prevStep">上一步</n-button>
              <n-button type="primary" :disabled="!termsAccepted" @click="submitUpload" :loading="submitting">
                提交素材
              </n-button>
            </n-space>
          </div>
        </n-tab-pane>
      </n-tabs>
    </n-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useMessage } from 'naive-ui'
import {
  NCard,
  NTabs,
  NTabPane,
  NButton,
  NForm,
  NFormItem,
  NInput,
  NInputNumber,
  NSelect,
  NCascader,
  NDynamicTags,
  NRadioGroup,
  NRadio,
  NSpace,
  NIcon,
  NText,
  NP,
  NUpload,
  NUploadDragger,
  NDivider,
  NAlert,
  NList,
  NListItem,
  NThing,
  NTag,
  NCheckbox
} from 'naive-ui'
import {
  ArrowBackOutline,
  CloudUploadOutline,
  InformationCircleOutline,
  AlertCircleOutline
} from '@vicons/ionicons5'

const router = useRouter()
const message = useMessage()

// 表单引用
const formRef = ref(null)

// 活动标签页
const activeTab = ref('basic')

// 是否接受条款
const termsAccepted = ref(false)

// 提交状态
const submitting = ref(false)

// 上传表单
const uploadForm = reactive({
  name: '',
  type: null,
  category: null,
  tags: [],
  description: '',
  isPaid: false,
  price: 10,
  license: 'standard'
})

// 上传文件
const uploadFiles = ref([])
const thumbnailFile = ref([])
const previewFiles = ref([])

// 表单验证规则
const rules = {
  name: {
    required: true,
    message: '请输入素材名称',
    trigger: 'blur'
  },
  type: {
    required: true,
    message: '请选择素材类型',
    trigger: 'change'
  },
  category: {
    required: true,
    message: '请选择素材分类',
    trigger: 'change'
  },
  description: {
    required: true,
    message: '请输入素材描述',
    trigger: 'blur'
  },
  license: {
    required: true,
    message: '请选择许可证类型',
    trigger: 'change'
  }
}

// 素材类型选项
const typeOptions = [
  { label: '角色', value: 'character' },
  { label: '场景', value: 'scene' },
  { label: '动作', value: 'action' },
  { label: '音效', value: 'sound' },
  { label: '特效', value: 'effect' },
  { label: '脚本', value: 'script' }
]

// 分类选项
const categoryOptions = [
  {
    label: '角色',
    value: 'character',
    children: [
      { label: '人物', value: 'human' },
      { label: '动物', value: 'animal' },
      { label: '机械', value: 'mech' },
      { label: '幻想生物', value: 'fantasy' }
    ]
  },
  {
    label: '场景',
    value: 'scene',
    children: [
      { label: '自然风光', value: 'nature' },
      { label: '城市建筑', value: 'city' },
      { label: '室内场景', value: 'interior' },
      { label: '抽象背景', value: 'abstract' }
    ]
  },
  {
    label: '动作',
    value: 'action',
    children: [
      { label: '行走', value: 'walk' },
      { label: '跑步', value: 'run' },
      { label: '跳跃', value: 'jump' },
      { label: '攻击', value: 'attack' },
      { label: '情感表达', value: 'emotion' }
    ]
  },
  {
    label: '音效',
    value: 'sound',
    children: [
      { label: '环境音效', value: 'ambient' },
      { label: '人物音效', value: 'character' },
      { label: '物体音效', value: 'object' },
      { label: '界面音效', value: 'ui' },
      { label: '音乐', value: 'music' }
    ]
  }
]

// 许可证选项
const licenseOptions = [
  { label: '标准许可 - 可用于个人和商业项目', value: 'standard' },
  { label: '扩展许可 - 可用于衍生商品和扩展分发', value: 'extended' },
  { label: '创作共用 - CC-BY', value: 'cc-by' },
  { label: '创作共用 - CC0 (公共领域)', value: 'cc0' }
]

// 下一步
function nextStep() {
  if (activeTab.value === 'basic') {
    formRef.value?.validate((errors) => {
      if (!errors) {
        activeTab.value = 'files'
      }
    })
  } else if (activeTab.value === 'files') {
    if (uploadFiles.value.length === 0) {
      message.warning('请至少上传一个素材文件')
      return
    }
    
    if (thumbnailFile.value.length === 0) {
      message.warning('请上传素材缩略图')
      return
    }
    
    activeTab.value = 'preview'
  }
}

// 上一步
function prevStep() {
  if (activeTab.value === 'files') {
    activeTab.value = 'basic'
  } else if (activeTab.value === 'preview') {
    activeTab.value = 'files'
  }
}

// 重置表单
function resetForm() {
  formRef.value?.restoreValidation()
  
  Object.assign(uploadForm, {
    name: '',
    type: null,
    category: null,
    tags: [],
    description: '',
    isPaid: false,
    price: 10,
    license: 'standard'
  })
  
  uploadFiles.value = []
  thumbnailFile.value = []
  previewFiles.value = []
}

// 返回市场
function goBack() {
  router.back()
}

// 提交上传
function submitUpload() {
  if (!termsAccepted.value) {
    message.warning('请先阅读并同意相关协议')
    return
  }
  
  submitting.value = true
  
  // 模拟上传过程
  setTimeout(() => {
    submitting.value = false
    message.success('素材上传成功，审核通过后会通知您')
    router.push('/market')
  }, 2000)
}

// 获取类型标签
function getTypeLabel(type) {
  const option = typeOptions.find(opt => opt.value === type)
  return option ? option.label : type
}

// 获取分类标签
function getCategoryLabel(categoryPath) {
  if (!categoryPath) return ''
  
  let result = ''
  let options = categoryOptions
  
  for (let i = 0; i < categoryPath.length; i++) {
    const value = categoryPath[i]
    const option = options.find(opt => opt.value === value)
    
    if (option) {
      result += (i > 0 ? ' > ' : '') + option.label
      options = option.children || []
    } else {
      break
    }
  }
  
  return result
}

// 获取许可证标签
function getLicenseLabel(license) {
  const option = licenseOptions.find(opt => opt.value === license)
  return option ? option.label : license
}

// 格式化文件大小
function formatFileSize(bytes) {
  if (!bytes) return '0 Bytes'
  
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 获取缩略图URL
function getThumbnailUrl(file) {
  if (file && file.url) {
    return file.url
  } else if (file && file.file) {
    return URL.createObjectURL(file.file)
  }
  return ''
}
</script>

<style lang="scss" scoped>
.creator-upload-container {
  padding: 20px;
  
  .upload-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      h1 {
        margin: 0;
        font-size: 24px;
      }
    }
  }
  
  .form-actions {
    margin-top: 24px;
  }
  
  .price-input {
    margin-top: 12px;
    width: 200px;
  }
  
  .upload-section {
    margin-bottom: 24px;
  }
  
  .upload-tips {
    margin-top: 16px;
  }
  
  .thumbnail-section,
  .preview-section {
    margin-bottom: 24px;
  }
  
  .thumbnail-upload,
  .preview-upload {
    display: flex;
    flex-direction: column;
    gap: 8px;
  }
  
  .preview-container {
    display: flex;
    flex-direction: column;
    gap: 16px;
  }
  
  .preview-item {
    display: grid;
    grid-template-columns: 120px 1fr;
    gap: 16px;
    
    .preview-label {
      font-weight: 500;
      color: var(--text-color-2);
    }
    
    .preview-value {
      &.description {
        white-space: pre-line;
      }
    }
  }
  
  .thumbnail-preview {
    width: 300px;
    height: 200px;
    overflow: hidden;
    border-radius: 4px;
    border: 1px solid var(--border-color);
    
    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }
  
  .submit-section {
    margin: 24px 0;
    
    .terms-checkbox {
      margin-top: 16px;
      display: block;
    }
  }
}

/* 响应式调整 */
@media (max-width: 768px) {
  .creator-upload-container {
    padding: 10px;
    
    .preview-item {
      grid-template-columns: 1fr;
      gap: 8px;
    }
    
    .thumbnail-preview {
      width: 100%;
      height: auto;
      aspect-ratio: 3/2;
    }
  }
}
</style> 